//
//  RegisterViewController.m
//  跨界收
//
//  Created by MT on 2018/10/27.
//  Copyright © 2018年 gztx. All rights reserved.
//

#import "RegisterViewController.h"
#import "AppDelegate.h"

@interface RegisterViewController ()

/**
 邀请码输入框
 */
@property (weak, nonatomic) IBOutlet UITextField *invitationCodeTextField;

/**
 手机号输入框
 */
@property (weak, nonatomic) IBOutlet UITextField *cellPhoneTextField;

/**
 验证码输入框
 */
@property (weak, nonatomic) IBOutlet UITextField *verificationCodeTextField;

/**
 勾选协议按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *selectAgreementButton;

/**
 注册按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *registerButton;

@property (weak, nonatomic) IBOutlet UIButton *codeBtn;

@end

@implementation RegisterViewController

#pragma mark - Lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self setup];
}

#pragma mark - Routine
- (void)setup
{
    self.title = @"注册";
    [self setupRegisterEnabled];
}

- (void)setupRegisterEnabled
{
    UIColor *blue = [UIColor cz_colorWithHex:0x467CEE];
    UIColor *gray = [UIColor cz_colorWithHex:0xc7c7c7];
    BOOL enabled = (self.cellPhoneTextField.text.length > 0 || self.invitationCodeTextField.text.length > 0 || self.verificationCodeTextField.text.length > 0);
    self.registerButton.backgroundColor = enabled ?  blue: gray;
    self.registerButton.enabled = enabled;
}

- (void)setupCountDown
{
    [self.codeBtn countdownTimerWithInterval:60 progressBlock:^(UIButton *sender, NSInteger time) {
        sender.userInteractionEnabled = NO;
        NSString *strTime = [NSString stringWithFormat:@"%.2d", (int)time];
        NSString *title = [NSString stringWithFormat:@"(%@s)",strTime];
        [sender setTitle:title forState:UIControlStateNormal];
    } successBlock:^(UIButton *sender) {
        sender.userInteractionEnabled = YES;
        [sender setTitle:@"获取验证码" forState:UIControlStateNormal];
    }];
}

- (void)closeKeyboard
{
    [self.cellPhoneTextField resignFirstResponder];
    [self.invitationCodeTextField resignFirstResponder];
    [self.verificationCodeTextField resignFirstResponder];
}

- (BOOL)isValidInput
{
    BOOL isInvitationCode = ![Tool isBlankString:self.invitationCodeTextField.text];
    BOOL isCellPhone = [Tool IsPhoneNumber:self.cellPhoneTextField.text];
    BOOL isVerificationCode = ![Tool isBlankString:self.verificationCodeTextField.text];
    
    if (!isInvitationCode) {
        [self showError:@"请输入邀请码"];
        return NO;
    }
    if (!isCellPhone) {
        [self showError:@"请输入正确的手机号"];
        return NO;
    }
    if (!isVerificationCode) {
        [self showError:@"请输入验证码"];
        return NO;
    }
    if (!self.selectAgreementButton.selected) {
        [self showError:[NSString stringWithFormat:@"请阅读并同意%@协议", kAppName]];
        return NO;
    }
    return YES;
}

#pragma mark - Action
- (IBAction)textFieldEditingChanged:(UITextField *)sender
{
    [self setupRegisterEnabled];
}

- (IBAction)fetchVerificationCode:(UIButton *)sender
{
    if (! [Tool IsPhoneNumber:self.cellPhoneTextField.text]) {
        [self showInfo:@"请输入正确的手机号"];
        return;
    }
    [self requestForSMS];
}

- (IBAction)didSelectedAgreementButton:(UIButton *)sender
{
    sender.selected = !sender.selected;
}

- (IBAction)gotoPreviewAgreement:(UIButton *)sender
{
    
}

- (IBAction)doRegister:(UIButton *)sender
{
    if (! [self isValidInput]) {
        return;
    }
    [self closeKeyboard];
    [self requestForRegister];
}

- (IBAction)backLogin:(UIButton *)sender {
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - Request
- (void)requestForSMS
{
    NSDictionary *parameters = @{ @"mobile": self.cellPhoneTextField.text, @"type": @(1) };
    [NetworkManager post:kSendSMSApi parameters:parameters success:^(id object) {
        [self showInfo:@"短信下发成功"];
        [self setupCountDown];
    } failure:^(NSError *error) {
        [self handleRequestFailure:error];
    }];
}

- (void)requestForRegister
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"account"] = self.cellPhoneTextField.text;
    dic[@"code"] = self.verificationCodeTextField.text;
    dic[@"invitationCode"] = self.invitationCodeTextField.text;
    
    [NetworkManager post:kRegisterApi parameters:dic success:^(id data) {
        [Tool setLocalDataValue:data[@"token"] key:kAccessTokenKey];
        [self requestForUserInfo];
    } failure:^(NSError *error) {
        [self handleRequestFailure:error];
    }];
}

- (void)requestForUserInfo
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"type"] = @(1);
    
    [NetworkManager post:kUserInfoApi parameters:dic success:^(id data) {
        UserModel *user = [UserModel modelWithJSON:data];
        [user saveToDisk];
        [[AppDelegate sharedDelegate] doLogin];
        [self showSuccess:@"注册成功"];
    } failure:^(NSError *error) {
        [self handleRequestFailure:error];
    }];
}

@end
